package cn.iocoder.yudao.module.system.controller.admin.tenantrechargelog;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.system.convert.tenant.TenantRechargeLogConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.tenant.TenantService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.system.controller.admin.tenantrechargelog.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.tenantrechargelog.TenantRechargeLogDO;
import cn.iocoder.yudao.module.system.service.tenantrechargelog.TenantRechargeLogService;

@Tag(name = "管理后台 - 租户充值记录")
@RestController
@RequestMapping("/system/tenant-recharge-log")
@Validated
public class TenantRechargeLogController {

    @Resource
    private TenantRechargeLogService tenantRechargeLogService;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private TenantService tenantService;

    @PostMapping("/create")
    @Operation(summary = "创建租户充值记录")
    @PreAuthorize("@ss.hasPermission('system:tenant-recharge-log:create')")
    public CommonResult<Long> createTenantRechargeLog(@Valid @RequestBody TenantRechargeLogSaveReqVO createReqVO) {
        if (Objects.isNull(createReqVO.getTenantId())) {
            createReqVO.setTenantId(TenantContextHolder.getTenantId());
        }
        return success(tenantRechargeLogService.createTenantRechargeLog(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新租户充值记录")
    @PreAuthorize("@ss.hasPermission('system:tenant-recharge-log:update')")
    public CommonResult<Boolean> updateTenantRechargeLog(@Valid @RequestBody TenantRechargeLogSaveReqVO updateReqVO) {
        tenantRechargeLogService.updateTenantRechargeLog(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除租户充值记录")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:tenant-recharge-log:delete')")
    public CommonResult<Boolean> deleteTenantRechargeLog(@RequestParam("id") Long id) {
        tenantRechargeLogService.deleteTenantRechargeLog(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得租户充值记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:tenant-recharge-log:query')")
    public CommonResult<TenantRechargeLogRespVO> getTenantRechargeLog(@RequestParam("id") Long id) {
        TenantRechargeLogDO tenantRechargeLog = tenantRechargeLogService.getTenantRechargeLog(id);
        return success(BeanUtils.toBean(tenantRechargeLog, TenantRechargeLogRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得充值记录分页")
    public CommonResult<PageResult<TenantRechargeLogRespVO>> getTenantRechargeLogPage(@Valid TenantRechargeLogPageReqVO pageReqVO) {
        if (Objects.isNull(pageReqVO.getTenantId())) {
            pageReqVO.setTenantId(TenantContextHolder.getTenantId());
        }
        PageResult<TenantRechargeLogDO> pageResult = tenantRechargeLogService.getTenantRechargeLogPage(pageReqVO);

        Map<Long, TenantDO> tenantMap = tenantService.getTenantMap(pageResult.getList().stream().map(TenantRechargeLogDO::getTenantId).collect(Collectors.toList()));

        Map<Long, AdminUserDO> userMap = TenantUtils.execute(1L, () -> adminUserService.getUserMap(pageResult.getList().stream().map(TenantRechargeLogDO::getOwnerUserId).collect(Collectors.toList())));
        PageResult<TenantRechargeLogRespVO> converted = TenantRechargeLogConvert.INSTANCE.convert(pageResult, userMap, tenantMap);
        return success(converted);
    }

    @GetMapping("/page-by-admin")
    @Operation(summary = "获得充值记录分页")
    @TenantIgnore
    public CommonResult<PageResult<TenantRechargeLogRespVO>> getTenantRechargeLogPageByAdmin(@Valid TenantRechargeLogPageReqVO pageReqVO) {
        PageResult<TenantRechargeLogDO> pageResult = tenantRechargeLogService.getTenantRechargeLogPage(pageReqVO);
        Map<Long, TenantDO> tenantMap = tenantService.getTenantMap(pageResult.getList().stream().map(TenantRechargeLogDO::getTenantId).collect(Collectors.toList()));
        Map<Long, AdminUserDO> userMap = TenantUtils.execute(1L, () -> adminUserService.getUserMap(pageResult.getList().stream().map(TenantRechargeLogDO::getOwnerUserId).collect(Collectors.toList())));
        PageResult<TenantRechargeLogRespVO> converted = TenantRechargeLogConvert.INSTANCE.convert(pageResult, userMap, tenantMap);
        return success(converted);
    }

    @GetMapping("/page-by-proxy")
    @Operation(summary = "获得充值记录分页")
    public CommonResult<PageResult<TenantRechargeLogRespVO>> getTenantRechargeLogPageByProxy(@Valid TenantRechargeLogPageReqVO pageReqVO) {
        if (Objects.isNull(pageReqVO.getTenantId())) {
            throw exception(new ErrorCode(100500, "必须指定客户查询"));
        }
        tenantService.validateTenantIsProxy(pageReqVO.getTenantId(), TenantContextHolder.getTenantId());
        PageResult<TenantRechargeLogDO> pageResult = TenantUtils.execute(pageReqVO.getTenantId(), () -> tenantRechargeLogService.getTenantRechargeLogPage(pageReqVO));
        Map<Long, TenantDO> tenantMap = tenantService.getTenantMap(pageResult.getList().stream().map(TenantRechargeLogDO::getTenantId).collect(Collectors.toList()));
        Map<Long, AdminUserDO> userMap = TenantUtils.execute(1L, () -> adminUserService.getUserMap(pageResult.getList().stream().map(TenantRechargeLogDO::getOwnerUserId).collect(Collectors.toList())));
        PageResult<TenantRechargeLogRespVO> converted = TenantRechargeLogConvert.INSTANCE.convert(pageResult, userMap, tenantMap);
        return success(converted);
    }


    @GetMapping("/simple-list")
    @Operation(summary = "获得充值记录列表")
    @Parameter(name = "tenantId", description = "编号列表", required = true)
    public CommonResult<List<TenantRechargeLogRespVO>> getTenantRechargeLogList(@RequestParam(value = "tenantId", required = false) Long tenantId) {
        if (Objects.isNull(tenantId)) {
            tenantId = TenantContextHolder.getTenantId();
        }
        List<TenantRechargeLogDO> pageResult = tenantRechargeLogService.getTenantRechargeLogList(tenantId);
        Map<Long, AdminUserDO> userMap = TenantUtils.execute(1L, () -> adminUserService.getUserMap(pageResult.stream().map(TenantRechargeLogDO::getOwnerUserId).collect(Collectors.toList())));
        Map<Long, TenantDO> tenantMap = tenantService.getTenantMap(pageResult.stream().map(TenantRechargeLogDO::getTenantId).collect(Collectors.toList()));
        List<TenantRechargeLogRespVO> result = pageResult.stream().map(item -> TenantRechargeLogConvert.INSTANCE.convert0(item, userMap,tenantMap)).collect(Collectors.toList());
        return success(BeanUtils.toBean(result, TenantRechargeLogRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出充值记录")
    @OperateLog(type = EXPORT)
    public void exportTenantRechargeLogExcel(@Valid TenantRechargeLogPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        if (Objects.isNull(pageReqVO.getTenantId())) {
            pageReqVO.setTenantId(TenantContextHolder.getTenantId());
        }
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<TenantRechargeLogDO> list = tenantRechargeLogService.getTenantRechargeLogPage(pageReqVO).getList();
        // 导出 Excel
        Map<Long, AdminUserDO> userMap = TenantUtils.execute(1L, () -> adminUserService.getUserMap(list.stream().map(TenantRechargeLogDO::getOwnerUserId).collect(Collectors.toList())));
        Map<Long, TenantDO> tenantMap = tenantService.getTenantMap(list.stream().map(TenantRechargeLogDO::getTenantId).collect(Collectors.toList()));

        List<TenantRechargeLogRespVO> result = list.stream().map(item -> TenantRechargeLogConvert.INSTANCE.convert0(item, userMap,tenantMap)).collect(Collectors.toList());
        ExcelUtils.write(response, "租户充值记录.xls", "数据", TenantRechargeLogRespVO.class,
                result);
    }

}